import ItemList from 'flarum/utils/ItemList';
import listItems from 'flarum/helpers/listItems';
import Button from 'flarum/components/Button';
import Separator from 'flarum/components/Separator';
import TextEditor from 'flarum/components/TextEditor';

/**
 * The `EnhancedTextEditor` component displays a textarea with controls, including a
 * submit button.
 *
 * ### Props
 *
 * - `submitLabel`
 * - `value`
 * - `placeholder`
 * - `disabled`
 */
export default class UEditor extends TextEditor {

    init() {
        this.value = m.prop(this.props.value || '');
        var resetEditContentHeight =
        setTimeout(() => {
            this.ue = new UE.ui.Editor();
            this.ue.render('ueEditor');
            this.ue.ready(() => {
                if(this.props.value) {
                    this.ue.setContent(this.props.value);
                    this.props.onchange(this.ue.getContent());
                }
                //显示按钮
                $('#composer>div>div.Composer-content>div>div.ComposerBody-content>div>div>ul').show();
            });
            this.ue.addListener('contentChange', () => {
                this.props.onchange(this.ue.getContent());
            });
            //适配高度
            $('.Composer-handle').mouseup(function () {
                var _h = parseInt($('#composer>div.Composer').css('height'))
                    -$('.edui-editor-bottomContainer').outerHeight()
                    -parseInt($('.Composer-content').css('padding-top'))
                    -$('.ComposerBody-header').outerHeight()
                    -$('.edui-editor-toolbarbox').outerHeight()
                    -3;
                $('#ueEditor>div.edui-editor>div.edui-editor-iframeholder').animate({'height': _h+'px'});
            });
        }, 100);
    }

    /**
     * 提交内容
     */
    onsubmit() {
        this.props.onsubmit(this.ue.getContent());
    }

    view() {
        return (
            <div className="TextEditor">
                <div id="ueEditor">
                </div>

                <ul className="TextEditor-controls Composer-footer">
                    {listItems(this.customerItems().toArray())}
                </ul>
            </div>
        );
    }

    /**
     * 自定义按钮
     */
    customerItems() {
        const items = new ItemList();

        items.add('submit',
            Button.component({
                children: this.props.submitLabel,
                icon: 'check',
                className: 'Button Button--primary',
                itemClassName: 'App-primaryControl',
                onclick: this.onsubmit.bind(this)
            })
        );

        return items;
    }
}
